var base = getApp();
var gid = 0;//商品ID
Page({
  data: {
    goodsDetail: {},
    bannerList: [],
    detailImgList: [],
    commentList:[],
    skuid:0,
    skuList:[],
    skuArr: [],//sku已选属性
    priceRange:"",//价格区间
    price: "",//价格
    pricef:0,//价格
    oprice:0,//原价
    tab: 0,
    likeList: [],
    isCollected: false,
    isEmpty: true,
    alertType: 'cart',
    changeNum: 1,
    url:base.path.url,
    img:"",
    show:0, //大图是否显示 1显示 0 不显示
    isStock:0,//是否有库存 0为没有 1为有
    moreComment:0,//是否显示更多评论
    scrollTop: 0,//距离顶部距离
    isLove:0,//是否喜欢
    floorstatus:false,
    animationData:{},//广告动画
    skuimg:"",
    stock:0,//当前库存
    skuname:[],//sku信息
    buydata:{},//
    isSku:0,//是否有SKU信息
    // likeCount:0,//喜欢的数量
    time:"",//抢购倒计时
  },
  // onPullDownRefresh: function () {
  //   wx.stopPullDownRefresh()
  // },

  /**
     * 页面加载时
     */
  onLoad: function (e) {
    var that = this;
    //转换html标签
    gid = e.id;
    var md5key="null";
    if (base.user.isAuthor==1){
      md5key = base.user.session_key;
    }
    wx.request({
      url: base.path.api + 'Goods.GetGoodsDetail',
      data: {
        gid: gid,
        aid: base.user.aid,
        md5key: md5key,
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
        var priceRange = "";
        var detailImgList = [];
        var pricef = 0;
        if (result.ret == 200) {

          if (result.data.min_sell_money == result.data.max_sell_money) {
            priceRange = "¥ " + base.returnFloat(result.data.min_sell_money);
            pricef = result.data.min_sell_money;
          } else {
            priceRange = "¥ " + base.returnFloat(result.data.min_sell_money) + " ~ ¥ " + base.returnFloat(result.data.max_sell_money);
          }
          if (!result.data.detail_imgs) {
            detailImgList = [];
          } else {
            detailImgList = result.data.detail_imgs;
          }
          // that.data.price = "¥" + result.data.min_sell_money + " ~ ¥" + result.data.max_sell_money;
          that.setData({
            goodsDetail: result.data,
            bannerList: result.data.banner_imgs,
            detailImgList: detailImgList,
            priceRange: priceRange,
            price: priceRange,
            pricef: pricef,
            oprice: base.returnFloat(result.data.market_price),
            isLove: result.data.has_like,
            skuimg: result.data.sku_img
          });
        } else {

        }
      }
    });
    that.getBuyData();
    that.getLikes();
    that.getComments();
    that.getTime();
    setInterval(function () {
      that.getTime();
    }, 1000);
  },

  // 倒计时
  getTime:function(){
    var start = new Date();
    start.setHours(24);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    var todayEndTime = Date.parse(start) / 1000;  
    var nowTime = Date.parse(new Date())/1000;
    var time = todayEndTime - nowTime;
    var h = Math.floor(time/3600);
    var m = Math.floor(time/60)%60;
    var s=Math.floor(time%60);
    if (h < 10) { h = "0" + h };
    if (m < 10) { m = "0" + m };
    if (s < 10) { s = "0" + s };
    this.setData({
      time: h + ":" + m + ":" + s
    })
  },
  // 返回顶部
 goTop: function (e) {
    this.setData({
      scrollTop: 0
    })
  },

 scrollTopFun: function (e) {
    // 容器滚动时将此时的滚动距离赋值给 this.data.scrollTop
    if (e.detail.scrollTop > 100) {
      this.setData({
        floorstatus: true
      });
    } else {
      this.setData({
        floorstatus: false
      });
    }
  },

 // 点击喜欢
 goHeart: function (e) {
   var that=this;
   var isLove=this.data.isLove;
   if(isLove==1){
     wx.showToast({
       title: '您已赞过，不能重复点赞！',
       icon: 'loading',
       duration: 1000
     });
     return;
   }
   wx.showToast({
     title: '点赞成功！',
     icon: 'success',
     duration: 1000
   });
   isLove=1;
   var like_count=parseInt(that.data.goodsDetail.like_count) + 1;
   that.data.goodsDetail.like_count=like_count;
   this.setData({
     isLove: isLove,
     goodsDetail: that.data.goodsDetail
   })
   wx.request({
     url: base.path.api + 'Goods.UserLike',
     data: {
       gid: gid,
       md5key: base.user.session_key
     },
     async: false,
     method: "POST",
     header: base.user.header,
     success: function (response) {
        console.log("success");
        that.getLikes();
     }
   })

   
 },

  // 获取喜欢用户头像
  getLikes:function(){
    var that=this;
    wx.request({
      url: base.path.api + 'Goods.GetLikes',
      data: {
        gid: gid,
        aid: base.user.aid
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (res) {
        var result = res.data;
        var likeList = [];
        if (result.data.length >= 0) {
          for (var i = 0; i < result.data.length; i++) {
            var headimg = "";
            if (result.data[i].indexOf("http") >= 0) {
              headimg = result.data[i];
            } else if (result.data[i] == "") {
              headimg = "/icon/photo.jpg";
            } else {
              headimg = that.data.url + result.data[i];
            }
            likeList.push(headimg)
          }
          that.setData({
            likeList: likeList,
          });
        }
      },
    });
  },


    // 获取用户评论
  getComments:function(){
    var that=this;
    wx.request({
      url: base.path.api + 'Goods.GetComments',
      data: {
        gid: gid,
        curpage: 1,
        size: 1
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (res) {
        var result = res.data;
        var commentList = [];
        if (result.data.length >= 0) {
          for (var i = 0; i < result.data.length; i++) {
            var nickname = "";
            var headimg = "";
            if (result.data[i].is_anonymous == 1) {
              nickname = "匿名用户";
            } else {
              nickname = result.data[i].nickname;
            }
            if (result.data[i].headimg.indexOf("http") >= 0) {
              headimg = result.data[i].headimg;
            } else {
              headimg = that.data.url + result.data[i].headimg;
            }
            var create_time = base.getDateList(parseInt(result.data[i].create_time), parseInt(result.data[i].now));
            commentList.push({ "content": result.data[i].content, "headimg": headimg, "star": result.data[i].star, "create_time": create_time, "nickname": nickname });
          }
          that.setData({
            commentList: commentList,
          });
        }
      },
    });
  },

    // 定时广告推送
  getBuyData:function(){
    var that=this;
    var t = setInterval(function () {
      wx.request({
        url: base.path.api + 'Goods.GetBuydata',
        data: {
          gid: gid,
        },
        async: false,
        method: "POST",
        header: base.user.header,
        success: function (response) {
          var result = response.data;
          if (result.ret == 200) {
            var buydata = {};
            buydata.nickname = result.data.nickname;
            buydata.city = result.data.city;
            buydata.second = result.data.second;
            that.setData({
              buydata: buydata
            });
            that.adPush();
          } else {
            clearInterval(t)
          }

        }
      })
    }, 20000);
  },
  /**
  * 广告推送
  */
  adPush: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,
      timingFunction: 'ease',
    });
    animation.top(10).opacity(1).step()
    that.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.top(-20).opacity(0).step();
      that.setData({
        animationData: animation.export()
      })
    }.bind(this), 2000);
  },
  
  goComment: function(e){
    wx.navigateTo({
      url: 'comment/comment?id=' + gid
    })
  },

  /**
   * 选中属性事件
   */
  onSelect: function (e) {
    var that=this;
    var id = e.currentTarget.dataset.id;
    var valid = e.currentTarget.dataset.valid;
    var attrName = e.currentTarget.dataset.attrname;
    var selected = e.currentTarget.dataset.value;
    var list = this.data.skuList;
    var skuArr = this.data.skuArr;
    var skuname = this.data.skuname;
    for(var k=0;k<list.length;k++) {
      if (list[k].attr_id == id) {
        list[k].selected = selected;
        skuArr[k]=parseInt(valid);
        skuname[k] = attrName + "：" + selected ;
        break;
      }
    }
    that.setData({
      skuList: list
    });
    //根据sku值查询价格
    if (skuArr.indexOf(0) < 0){
      that.data.skuname = skuname;
      that.skuSelect(skuArr);
    }
    
  },
skuSelect:function(skuArr){
  var that=this;
  wx.request({
    url: base.path.api + 'Goods.GetSkuInfo',
    data: {
      gid: gid,
      aid: base.user.aid,
      valid: skuArr.join(",")
    },
    async: false,
    method: "POST",
    header: base.user.header,
    success: function (response) {
      var result = response.data;
      if (result.ret == 200) {
        var price = result.data[0].youhui_money;
        var skuid = result.data[0].skuid;
        var goodsnum = result.data[0].goodsnum;
        var warmnum = result.data[0].warmnum;
        var stock = goodsnum - warmnum;
        var skuimg = result.data[0].skuimg;
        if(skuimg==""){
          skuimg=that.data.skuimg;
        }
        var is_alive = result.data[0].is_alive;
        var isStock = 0;
        if (stock <= 0 || is_alive != 1) {
          stock=0;
          wx.showToast({
            title: "库存不足，请重新选择",
            icon: 'loading',
            duration: 1000
          });
          isStock = 0;
        } else {
          isStock = 1;
        }
        that.data.skuid = skuid;
        that.setData({
          price: "¥" + price,
          pricef: price,
          isStock: isStock,
          skuimg: skuimg,
          stock: stock,
          changeNum: 1,
        });

      } else {
        wx.showToast({
          title: result.msg,
          icon: 'loading',
          duration: 1000
        });
      }
    }
  })
},

//分享
  onShareAppMessage: function () {
    var that=this;
    return {
      title: that.data.goodsDetail.advertising,
      desc: that.data.goodsDetail.advertising,
      path: 'pages/goods_detail/goods_detail?id=' + gid,
      imageUrl: that.data.url+that.data.bannerList[0],
      success: function (res) {
        // 转发成功
        console.log(that.data.goodsDetail.advertising+","+gid)
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  goShare: function(){
    var that=this;
    that.onShareAppMessage();
  },

  /**
   * tab切换
   */
  changeTab: function (e) {
    var d = e.currentTarget.dataset.index;
    this.setData({
      tab: d
    });
  },

  /**
   * 加入购物车
   */
  addCart: function (e) {
    var that = this;
    var skuArr=that.data.skuArr;
    if (skuArr.indexOf(0) > -1) {
      wx.showModal({
        title: '',
        content: "尚未选择规格",
        showCancel: false,
        success: function (res) {
        }
      });
      return;
    }
    base.user.user_id = wx.getStorageSync('user_id');
    wx.request({
      url: base.path.api + 'ShopCart.AddCart',
      data: {
        gid: gid,
        quantity: that.data.changeNum,
        skuid: that.data.skuid,
        md5key: base.user.session_key,
        uid: base.user.user_id,
        aid: base.user.aid,
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
        if (result.ret == 200) {
          wx.showModal({
            title: '加入成功！',
            content: "跳转到购物车或留在当前页",
            showCancel: true,
            cancelText: "留在此页",
            confirmText: "去购物车",
            success: function (res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '../cart/cart',
                });
              }
            }
          });
        } else {
          wx.showToast({
            title: result.msg,
            icon: 'loading',
            duration: 1000
          });
        }
      }
    });
  },

  /**
   * 更改数量
   */
  changeNum: function (e) {
    var that=this;
    var num = parseInt(e.currentTarget.dataset.num);
    var isStock=that.data.isStock;
    var stock=that.data.stock;
    if (num == 1) {
      num = that.data.changeNum + 1;
    } else if (num == -1) {
      num = that.data.changeNum - 1
      if (num <= 0) {
        return false;
      }
    } else {
      return false;
    }
    if (num > stock){
      isStock=0;
    }else{
      isStock=1
    }
    that.setData({
      changeNum: num,
      isStock:isStock
    })
  },

  /**
   * 去购物车
   */
  goCart: function () {
    wx.switchTab({
      url: '../cart/cart',
    })
  },

  /**
   * 回首页
   */
  goIndex: function () {
    wx.switchTab({
      url: '../index/index'
    });
  },

  /**
   * 去购买
   */
  goBuy: function () {
    var that = this;
    var skuArr = that.data.skuArr;
    if (skuArr.indexOf(0) > -1) {
      wx.showModal({
        title: '',
        content: "尚未选择规格",
        showCancel: false,
        success: function (res) {
        }
      });
      return;
    }
    var list = [];
    var obj = {
      goods_id: gid,
      goods_num: that.data.changeNum,
      name: that.data.goodsDetail.name,
      sell_money: that.data.pricef,
      skuid: that.data.skuid,
      skuimg: that.data.skuimg,
      skuname: that.data.skuname.join("，")
    };
    list.push(obj);
    wx.setStorageSync('buy_info', list);
    that.getBeforeOrder();
    wx.navigateTo({
      url: "../order/order?type=buy",
    })
  },

  //统计older页的商品、用户信息及来源
  getBeforeOrder: function () {
    wx.request({
      url: base.path.api + 'Order.BeforeOrder',
      data: {
        md5key: base.user.session_key,
        aid: base.user.aid,
        gid:gid
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
      }
    });
  },

  goDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../goods_detail/goods_detail?id=' + id
    })
  },

  myaddrChange: function (e) {//选择sku
    var alertType = e.currentTarget.dataset.type;
    this.skuShow(this,alertType);
    // var skuid=this.data.skuid;//是否有sku
  },

  // sku查询
  skuShow: function (that, alertType){
    wx.request({
      url: base.path.api + 'Goods.GetGoodsSku',
      data: {
        gid: gid,
        aid: base.user.aid
      },
      async: false,
      method: "POST",
      header: base.user.header,
      success: function (response) {
        var result = response.data;
        var isSkuid=0;
        if (result.ret == 200) {
          var skuArr = [];
          var skuname = [];
          if (result.data.length == 1){
            var isSkuid = result.data[0].skuid;
            skuArr.push(result.data[0].val_id);
            that.skuSelect(skuArr);
            that.setData({
              skuid: isSkuid,
              sell_money: that.data.pricef,
              addrShow: false,
              alertType: alertType,
              isSku:0
            })
            that.goBuy();
          }else if (result.data.length>1){
            var skuData=[];//sku数据格式重新排列
            var skuType=[];//sku属性
            for (var i = 0; i < result.data.length; i++) {
              var attr_name = result.data[i].attr_name;
              if (skuType.indexOf(attr_name)>-1){
                // skuData.push(skuChild);
              }else{
                skuType.push(attr_name);
              }
            }
            for (var j = 0; j < skuType.length; j++) {
              var skuDatai = {};
              var skuCon = [];
              for (var i = 0; i < result.data.length; i++) {
                var attr_name = result.data[i].attr_name;
                var val_name = result.data[i].val_name;
                var val_id = result.data[i].val_id;
                var skuid = result.data[i].skuid
                if (skuType[j] == attr_name) {
                  var coni = {};
                  coni.val_id = val_id;
                  coni.val_name = val_name;           
                  coni.skuid = skuid;           
                  skuCon.push(coni);
                }
              }
              skuDatai.attr_name = skuType[j];
              skuDatai.attr_id = j;
              skuDatai.selected = "";
              skuDatai.con = skuCon;
              skuData.push(skuDatai);
              that.data.skuArr.push(0);
            }
            that.data.skuid =skuData[0].con[0].skuid;

            
            for (var i = 0; i < skuData.length; i++) {
              skuData[i].selected = skuData[i].con[0].val_name;
              skuArr.push(skuData[i].con[0].val_id);
              skuname.push(skuData[i].attr_name +"："+ skuData[i].con[0].val_name);
            }
            that.skuSelect(skuArr);
            that.setData({
              addrShow: true,
              skuList: skuData,
              skuArr:skuArr,
              skuname: skuname,
              isSku: 1,
              alertType: alertType,
            })
          }
          // if (isSkuid != 0) {
          //   if (alertType == 'cart') {
          //     that.addCart();
          //   } else {
          //     that.goBuy();
          //   }
          //   return true;
          // } else {
          //   that.setData({
          //     addrShow: true,
          //     alertType: alertType
          //   });
          // }
        }else {
          wx.showToast({
            title: result.msg,
            icon: 'loading',
            duration: 1000
          });
        }
      }
    });
  },
  myaddrCancel: function () {//点击X取消按钮
    var that=this;
    that.setData({
      skuid: 0,
      skuList: [],
      skuArr: [],//sku已选属性
      detail: [],
      stock: 0,
      addrShow: false ,
      price: that.data.priceRange,
      isStock : 0
    });

  },
  closeaddr: function () {//触摸遮罩层关闭地址选项
    this.setData({ addrShow: false });
  },




});